from PyQt5.QtCore import Qt
from PyQt5.QtGui import QFont, QDesktopServices
from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QTableWidget, QTableWidgetItem,
                             QTextEdit, QSizePolicy, QHeaderView)
from base_pagination_view import BasePaginationView


class BookView(QWidget, BasePaginationView):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.parent = parent
        self.table = None
        self.current_page = 1
        self.total_pages = 1
        self.page_size = 10
        self.init_ui()

    def init_ui(self):
        """初始化UI组件"""
        layout = QVBoxLayout(self)
        layout.setContentsMargins(10, 10, 10, 10)
        layout.setSpacing(10)

        # 初始化表格
        self.table = QTableWidget()
        self.table.setRowCount(0)
        self.table.setColumnCount(5)
        layout.addWidget(self.table, stretch=1)

        # 添加分页控制栏
        self.init_pagination_controls(layout)

        # 设置表格字体
        font = self.table.font()
        font.setPointSize(self.parent.default_font_size)
        self.table.setFont(font)

        # 设置表头字体
        header_font = self.table.horizontalHeader().font()
        header_font.setPointSize(self.parent.default_font_size)
        self.table.horizontalHeader().setFont(header_font)

        # 设置表格尺寸策略
        self.table.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Interactive)
        self.table.verticalHeader().setSectionResizeMode(QHeaderView.Interactive)
        self.table.horizontalHeader().setStretchLastSection(True)

    def fetch_data(self):
        """获取数据"""
        return self.parent.fetch_data(page=self.current_page, page_size=self.page_size)

    def setup_table(self, data, column_widths=None):
        """设置书籍表格并更新分页信息"""
        self.table.setColumnCount(5)
        self.table.setHorizontalHeaderLabels(["序号", "书本ID", "书名", "创建时间", "操作"])
        self.table.setRowCount(len(data["list"]))

        # 设置列宽
        header = self.table.horizontalHeader()
        if column_widths and len(column_widths) == 5:
            # 使用自定义百分比宽度
            total_width = self.table.width()
            for col, width_pct in enumerate(column_widths):
                header.resizeSection(col, int(total_width * width_pct / 100))
        else:
            column_widths = [10, 10, 40, 30, 10]
            self.setup_table(data, column_widths=column_widths)

        # 填充数据
        for row_idx, book in enumerate(data["list"]):
            self.fill_row(row_idx, book)

        # 连接窗口大小变化信号
        self.parent.resized.connect(self.adjust_table_columns)

        # 计算总页数
        total_items = data.get("total", len(data["list"]))
        self.total_pages = max(1, (total_items + self.page_size - 1) // self.page_size)

        # 仅当data中有current_page时才更新当前页
        if "current_page" in data:
            self.current_page = data["current_page"]

        self.update_pagination_controls()

    def update_pagination_controls(self):
        """更新分页控制组件状态"""
        print(f"更新分页状态 - 当前页: {self.current_page}, 总页数: {self.total_pages}")
        self.page_label.setText(f"第{self.current_page}页")
        self.total_pages_label.setText(f"共{self.total_pages}页")
        self.page_spin.setMaximum(self.total_pages)
        self.page_spin.setValue(self.current_page)

        # 更新按钮状态
        print(f"更新分页状态 - 当前页: {self.current_page}, 总页数: {self.total_pages}")
        prev_enabled = self.current_page > 0
        next_enabled = self.current_page < self.total_pages
        print(f"按钮状态 - 上一页: {prev_enabled}, 下一页: {next_enabled}")

        self.prev_btn.setEnabled(prev_enabled)
        self.next_btn.setEnabled(next_enabled)

    def go_to_prev_page(self):
        """跳转到上一页"""
        print(f"尝试跳转到上一页，当前页: {self.current_page}")
        if hasattr(self.parent, 'show_status_message'):
            self.parent.show_status_message(f"尝试跳转到上一页，当前页: {self.current_page}")
        if self.current_page < 2:
            return  # 防止越界
        if self.current_page > 1:
            self.current_page -= 1
            print(f"加载第{self.current_page}页数据")
            if hasattr(self.parent, 'show_status_message'):
                self.parent.show_status_message(f"加载第{self.current_page}页数据")
            self.parent.fetch_data(page=self.current_page, page_size=self.page_size)
            self.update_pagination_controls()

    def go_to_next_page(self):
        """跳转到下一页"""
        print(f"[调试] 开始跳转下一页 - 当前页: {self.current_page}, 总页数: {self.total_pages}")
        if hasattr(self.parent, 'show_status_message'):
            self.parent.show_status_message(f"尝试跳转到下一页，当前页: {self.current_page}")

        if self.current_page < self.total_pages:
            new_page = self.current_page + 1
            print(f"[调试] 准备加载新页 - new_page: {new_page}, 当前current_page: {self.current_page}")

            # 先更新current_page
            self.current_page = new_page
            print(f"[调试] 更新后current_page: {self.current_page}")

            # 调用fetch_data
            data = self.parent.fetch_data(page=self.current_page, page_size=self.page_size)
            print(f"[调试] fetch_data返回后current_page: {self.current_page}")

            # 强制保持当前页设置
            self.current_page = new_page

            if data:
                # 更新表格但不修改分页状态
                self.setup_table_without_paging(data)
            else:
                print(f"警告: fetch_data返回空数据，保持当前页: {self.current_page}")

            # 更新分页状态
            self.update_pagination_controls()
            print(f"[调试] update_pagination_controls后current_page: {self.current_page}")

    def go_to_page(self, page):
        """跳转到指定页码"""
        if 1 <= page <= self.total_pages and page != self.current_page:
            self.current_page = page
            self.parent.fetch_data(page=self.current_page, page_size=self.page_size)

    def change_page_size(self, size):
        """更改每页显示数量"""
        self.page_size = int(size)
        self.current_page = 1
        self.parent.fetch_data(page=self.current_page, page_size=self.page_size)

    def fill_row(self, row_idx, book):
        """填充书籍表格行"""
        for col_idx in range(4):
            item = QTableWidgetItem()
            if col_idx == 0:
                item.setText(str(row_idx + 1))
            elif col_idx == 1:
                item.setText(str(book["id"]))
            elif col_idx == 2:
                item.setText(book["book_name"])
            elif col_idx == 3:
                item.setText(book["create_time"])
            item.setTextAlignment(Qt.AlignCenter)
            self.table.setItem(row_idx, col_idx, item)

        # 创建按钮容器
        from PyQt5.QtWidgets import QWidget, QHBoxLayout
        button_widget = QWidget()
        button_widget.setProperty('class', 'theme-aware')  # 添加主题感知属性
        button_layout = QHBoxLayout(button_widget)
        button_layout.setContentsMargins(0, 0, 0, 0)
        button_layout.setSpacing(7) # 按钮的间距

        # 编辑按钮
        edit_button = self.parent.create_button("编辑",
                                              lambda checked, bid=book["id"]: self.parent.show_chapter_list(bid),
                                              is_edit=False)
        edit_button.setStyleSheet("""
            QPushButton {
                color: palette(windowText);
                background-color: palette(button);
                border: 1px solid palette(mid);
                padding: 3px;
                min-width: 50px;
            }
            QPushButton:hover {
                background-color: palette(light);
            }
            QPushButton:pressed {
                background-color: palette(dark);
            }
            QPushButton:disabled {
                color: palette(disabledText);
                background-color: palette(disabled);
            }
        """)
        edit_button.setProperty('class', 'theme-aware')
        button_layout.addWidget(edit_button)

        # 导出按钮
        export_button = self.parent.create_button("导出",
                                               lambda checked, bid=book["id"]: self.export_book(bid),
                                               is_edit=False)
        export_button.setStyleSheet("""
            QPushButton {
                color: palette(windowText);
                background-color: palette(button);
                border: 1px solid palette(mid);
                padding: 3px;
                min-width: 50px;
            }
            QPushButton:hover {
                background-color: palette(light);
            }
            QPushButton:pressed {
                background-color: palette(dark);
            }
            QPushButton:disabled {
                color: palette(disabledText);
                background-color: palette(disabled);
            }
        """)
        export_button.setProperty('class', 'theme-aware')
        button_layout.addWidget(export_button)

        # 将按钮容器设置到操作列
        self.table.setCellWidget(row_idx, 4, button_widget)

    def export_book(self, book_id):
        """导出书籍为zip文件"""
        from PyQt5.QtWidgets import QFileDialog, QProgressDialog
        from PyQt5.QtCore import QUrl
        import requests
        import os

        # 选择保存路径
        save_path, _ = QFileDialog.getSaveFileName(self.parent, "保存导出文件",
                                                   f"book_{book_id}.zip",
                                                   "Zip Files (*.zip)")
        if not save_path:
            return

        # 创建进度对话框
        progress = QProgressDialog("正在导出书籍...", "取消", 0, 100, self.parent)
        progress.setWindowTitle("导出进度")
        progress.setWindowModality(True)
        progress.show()

        try:
            # 调用saveChapter接口保存数据
            data = {
                'book_id': book_id,
            }
            response = requests.post('http://127.0.0.1:5000/exportBook', json=data, stream=True)

            if response.status_code == 200:
                print("章节内容保存成功")
            else:
                print(f"保存章节内容失败: {response.text}")
                raise Exception(f"API调用失败: {response.text}")
            response.raise_for_status()
            total_size = int(response.headers.get('content-length', 0))
            downloaded = 0

            # 写入文件并更新进度
            with open(save_path, 'wb') as f:
                for chunk in response.iter_content(chunk_size=8192):
                    if chunk:
                        f.write(chunk)
                        downloaded += len(chunk)
                        progress.setValue(int(downloaded / total_size * 100))
                        if progress.wasCanceled():
                            os.remove(save_path)
                            return

            progress.setValue(100)
            progress.close()

            # 打开保存目录
            QDesktopServices.openUrl(QUrl.fromLocalFile(os.path.dirname(save_path)))

        except Exception as e:
            progress.close()
            from PyQt5.QtWidgets import QMessageBox
            QMessageBox.critical(self.parent, "导出失败", f"导出书籍时出错: {str(e)}")

    def log_message(self, message, level):
        """记录日志消息"""
        if hasattr(self.parent, 'log_message') and callable(self.parent.log_message):
            self.parent.log_message(message, level)

    def adjust_table_columns(self, column_widths=None):
        """响应窗口大小变化，调整表格列宽
        :param column_widths: 列宽百分比列表，如[10, 15, 40, 15, 20]
        """
        column_widths = [10, 10, 40, 30, 10]
        if hasattr(self, 'table') and self.table:
            header = self.table.horizontalHeader()
            if column_widths and len(column_widths) == 5:
                # 使用自定义百分比宽度
                total_width = self.table.width()
                for col, width_pct in enumerate(column_widths):
                    header.resizeSection(col, int(total_width * width_pct / 100))
            else:
                # 默认宽度策略
                header.setSectionResizeMode(0, QHeaderView.ResizeToContents)
                header.setSectionResizeMode(1, QHeaderView.ResizeToContents)
                header.setSectionResizeMode(2, QHeaderView.Stretch)
                header.setSectionResizeMode(3, QHeaderView.ResizeToContents)
                header.setSectionResizeMode(4, QHeaderView.ResizeToContents)

    def setup_table_without_paging(self, data, column_widths=None):
        """设置书籍表格但不更新分页信息"""
        self.table.setColumnCount(5)
        self.table.setHorizontalHeaderLabels(["序号", "书本ID", "书名", "创建时间", "操作"])
        self.table.setRowCount(len(data["list"]))

        # 设置列宽
        header = self.table.horizontalHeader()
        if column_widths and len(column_widths) == 5:
            # 使用自定义百分比宽度
            total_width = self.table.width()
            for col, width_pct in enumerate(column_widths):
                header.resizeSection(col, int(total_width * width_pct / 100))
        else:
            column_widths = [10, 10, 40, 30, 10]  # 序号15%, ID15%, 书名40%, 时间15%, 操作15%
            self.setup_table_without_paging(data, column_widths=column_widths)

        # 填充数据
        for row_idx, book in enumerate(data["list"]):
            self.fill_row(row_idx, book)